package com.gome.axwl.aoc.common.util;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 集合工具类
 *
 * @author wangjie36@gome.com.cn
 * @date 2018/3/8
 * @copyright(c) gome inc Gome Co.,LTD
 */
public class CollectionUtil {

    private static final Logger LOGGER=LoggerFactory.getLogger(CollectionUtil.class);
    /**
     * 获取集合Collection中重复的对象
     *
     * @author wangjie36@gome.com.cn
     * @date 2018/3/9
     * @param collection 集合
     * @return 包含重复对象的流
     */
//    public static Stream<?> getRepeatElements(Collection<?> collection) {
//        return collection.stream()
//                .collect(Collectors.toMap(e -> e, e -> 1, (a, b) -> a + b)) // 获得元素出现频率的 Map，键为元素，值为元素出现的次数
//                .entrySet().stream()                   // 所有 entry 对应的 Stream
//                .filter(entry -> entry.getValue() > 1) // 过滤出元素出现次数大于 1 的 entry
//                .map(entry -> entry.getKey());          // 获得 entry 的键（重复元素）对应的 Stream
//    }

    /**
     * 内存分页
     * @param list
     * @param currPageNo
     * @param pageSize
     * @Auther: yinyuxin@gome.com.cn
     * @param <T>
     * @return
     */
    public static  <T> Map<String, Object> getPagingResultMap(List<T> list, Integer currPageNo, Integer pageSize) {
        Map<String, Object> retMap = new HashMap<>();

        try {
            if (list.isEmpty()) {
                retMap.put("data", Collections.emptyList());
                retMap.put("pageNum", 0);
                retMap.put("pageSize", 0);
                retMap.put("total", 0);
                retMap.put("pages", 0);
                return retMap;
            }
            int totalRowNum = list.size();
            int totalPageNum = (totalRowNum - 1) / pageSize + 1;
            int realPageNo = currPageNo;
            if (currPageNo > totalPageNum) {
                realPageNo = totalPageNum;
            } else if (currPageNo < 1) {
                realPageNo = 1;
            }
            int fromIdx = (realPageNo - 1) * pageSize;
            int toIdx = totalPageNum * pageSize > totalRowNum ? totalRowNum : realPageNo * pageSize;
            List<T> result = list.subList(fromIdx, toIdx);
            retMap.put("data", result);
            retMap.put("pageNum", realPageNo);
            retMap.put("pageSize", result.size());
            retMap.put("total", totalRowNum);
            retMap.put("pages", totalPageNum);
            return retMap;
        } catch (Exception e) {
            LOGGER.error("CollectionsUtil-->getPagingResultMap()-->error:{}",ExceptionUtils.getFullStackTrace(e));
            throw new RuntimeException();
        }
    }
}
